<template>
  <div id="layout">
    <el-container>
      <!-- 顶部导航栏 -->
      <el-header class="header">
        <div class="header-left">
          <span class="header-title">侦察攻击训练武器载荷库</span>
        </div>
        <div class="header-right">
          <el-avatar class="user-avatar" icon="el-icon-user"></el-avatar>
          <span class="username">{{ username }}</span>
          <el-button type="danger" size="mini" class="logout-button" @click="logout">
            退出登录
          </el-button>
        </div>
      </el-header>

      <el-container>
        <!-- 左侧菜单栏 -->
        <el-aside width="240px" class="left">
          <el-menu
            class="el-menu-vertical-demo"
            background-color="#2a4aa4"
            text-color="#fff"
            active-text-color="#ffd04b"
            router
            unique-opened
            :collapse-transition="true"
            :default-active="activeMenu"
          >
            <!-- 遍历菜单 -->
            <template v-for="item in leftList">
              <!-- 有子菜单 -->
              <el-submenu v-if="item.children" :key="item.id" :index="item.url || ''">
                <template slot="title">
                  <i class="iconfont" v-html="item.icon"></i>
                  <span>{{ item.name }}</span>
                </template>
                <el-menu-item
                  v-for="child in item.children"
                  :key="child.id"
                  :index="child.url || ''"
                  @click="handleMenuClick(child)"
                >
                  <i class="iconfont" v-html="child.icon"></i>
                  <span>{{ child.name }}</span>
                </el-menu-item>
              </el-submenu>
            </template>
          </el-menu>
        </el-aside>

        <!-- 右侧内容区 -->
        <el-main class="main-content">
          <router-view></router-view>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>
import $axios from "@/unil/index.js";
import { mapActions, mapGetters } from "vuex";

export default {
  name: "layoutIndex",
  data() {
    return {
      leftList: [],
      activeMenu: "", // 当前激活的菜单项
    };
  },
  computed: {
    ...mapGetters("permissions", ["getUsername"]), // 获取用户名
    username() {
      return this.getUsername; // 显示用户名
    },
  },
  created() {
    this.fetchUserResources();
    this.activeMenu = this.$route.path; // 初始化激活菜单项为当前路由路径
  },
  watch: {
    // 监听路由变化，更新激活菜单项
    $route(to) {
      this.activeMenu = to.path;
    },
  },
  methods: {
    ...mapActions("permissions", ["setPermissions", "setUsername", "setIsManager"]),
    async fetchUserResources() {
      const token = localStorage.getItem("token");
      if (!token) {
        console.error("Token 未定义，请检查登录状态");
        this.$router.push("/login");
        return;
      }

      try {
        const res = await $axios.get("/user/getRes", { params: { token } });
        
        // 确保明确转换为数字类型，并使用action更新
        const isManager = Number(res.data.data.isManager);
        console.log("获取到的isManager:", isManager, typeof isManager);
        
        // 使用mapActions映射的action来更新isManager
        this.setIsManager(isManager);
        
        // 立即检查设置后的效果
        console.log("设置后的isAdmin:", this.$store.getters["permissions/isAdmin"]);
        console.log("设置后的isManager:", this.$store.state.permissions.isManager);
        
        if (res.data && res.data.data.sysResourcesMap) {
          const resources =
            res.data.data.sysResourcesMap.admin || res.data.data.sysResourcesMap.pro;
          this.leftList = resources.filter((item) => item.type === "menu");
          console.log("用户资源列表:", this.leftList);
          

          const buttons = [];
          this.leftList.forEach((item) => {
            item.children?.forEach((child) => {
              child.children?.forEach((grand) => {
                buttons.push(grand.permission); // 假设按钮权限存储在 permission 字段中
              });
            });
          });
          
          const username = res.data.data.username;
          this.setUsername(username); // 存储用户名到 Vuex
          localStorage.setItem("username", username); // 持久化用户名
          this.setPermissions(buttons); // 根据用户名更新权限
          localStorage.setItem("permissions", JSON.stringify(buttons)); // 持久化权限信息
          // 移除localStorage直接设置，由mutation处理
          // localStorage.setItem("isManager", isManager);
        }
      } catch (error) {
        console.error("获取用户列表失败:", error);
      }
    },

    handleMenuClick(item) {
      if (item.url) {
        this.$router.push(item.url).catch((err) => {
          if (err.name !== "NavigationDuplicated") {
            console.error(err);
          }
        });
      }
    },

    logout() {
      console.log("退出登录");
      localStorage.removeItem("token");
      localStorage.removeItem("username"); // 清除用户名
      localStorage.removeItem("permissions"); // 清除权限信息
      localStorage.removeItem("isManager"); // 确保清除isManager
      this.$router.push("/login");
    },
  },
};
</script>

<style lang="scss" scoped>
.left {
  background-color: #2a4aa4; /* 深蓝色背景 */
  height: calc(100vh - 60px);
  overflow: hidden;
  box-shadow: 2px 0 4px rgba(0, 0, 0, 0.1);
  border-top-right-radius: 30px;    // 添加右上圆角
  border-bottom-right-radius: 30px; /* 添加右下圆角 */
}

.el-menu-vertical-demo {
  border-right: none;
  background-color: #2a4aa4 !important; /* 统一背景色 */
}

.el-menu-item,
.el-submenu__title {
  font-size: 14px;
  font-weight: 500;
  color: #fff; /* 白色字体 */
  border-radius: 20px /* 默认无圆角 */
}

.el-menu-item:hover,
.el-submenu__title:hover {
  background-color: #1f2d3d !important; /* 深蓝色悬停背景 */
}

.el-menu-item.is-active {
  background-color: #000 !important; /* 黑色选中背景 */
  color: #fff !important; /* 白色字体 */
  border-radius: 20px; /* 椭圆形 */
}

.el-submenu__title.is-active {
  background-color: #000 !important; /* 黑色选中背景 */
  color: #fff !important; /* 白色字体 */
  border-radius: 20px; /* 椭圆形 */
}

.iconfont {
  font-family: "iconfont" !important;
  font-size: 20px;
  color: #fff;
  margin-right: 5px;
}

.header {
  background-color: #131313;
  color: #fff;
  font-size: 18px;
  padding: 15px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-left {
  display: flex;
  align-items: center;
}

.header-icon {
  font-size: 24px;
  margin-right: 10px;
  color: #ffd04b;
}

.header-title {
  font-weight: bold;
}

.header-right {
  display: flex;
  align-items: center;
}

.user-avatar {
  margin-right: 10px;
  background-color: #2a4aa4;
}

.username {
  margin-right: 15px;
  font-size: 14px;
  color: #fff;
}

.logout-button {
  background-color: #ff4d4f;
  color: #fff;
  border: none;
  &:hover {
    background-color: #ff7875;
  }
}

.left {
  background-color: #2a4aa4; /* 深蓝色背景 */
  height: calc(100vh - 60px);
  overflow: hidden;
  box-shadow: 2px 0 4px rgba(0, 0, 0, 0.1);
  border-top-right-radius:30px;    // 添加右上圆角
  border-bottom-right-radius: 30px; /* 添加右下圆角 */
}

.el-menu-vertical-demo {
  border-right: none;
  background-color: #2a4aa4 !important; /* 统一背景色 */
}

.el-menu-item,
.el-submenu__title {
  font-size: 14px;
  font-weight: 500;
}

.el-menu-item:hover,
.el-submenu__title:hover {
  background-color: #1f2d3d !important;
}

.main-content {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background-color: #262626;
  height: calc(100vh - 64px);
  box-sizing: border-box;
}

.iconfont {
  font-family: "iconfont" !important;
  font-size: 20px;
  color: #fff;
  margin-right: 5px;
}

body {
  background-color: #f0f2f5;
}
</style>
